package com.ibangnuo.manage.config.shiro;

import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: wwy
 * @Date: 2019-12-30 16:54
 */
public class ShiroFormAuthenticationFilter extends FormAuthenticationFilter {
    public static final String DEFAULT_PATH_SEPARATOR = "/";

    private String pathSeparator = DEFAULT_PATH_SEPARATOR;
  /*  @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return false;
    }*/

    /**
     * 重写验证失效后
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                return executeLogin(request, response);
            } else {
                return true;
            }
        } else {
            String requestURI = getPathWithinApplication(request);
            System.out.println(requestURI);
            HttpServletRequest httpServletRequest = (HttpServletRequest)request;
            System.out.println(httpServletRequest.getContextPath());
            String[] pattDirs = StringUtils.tokenizeToStringArray(requestURI, this.pathSeparator);
            //是ajax请求重定向
            if(isAjax(request)){
                //if(pattDirs.length>0&&!"system".equals(pattDirs[0])) {
                HttpServletResponse httpServletResponse = (HttpServletResponse)response;
                httpServletResponse.sendRedirect("/views/login/admin-login.html");
                //}
            }else{
            //针对前段请求window.location.href
                HttpServletResponse httpServletResponse = (HttpServletResponse)response;
                httpServletResponse.sendRedirect("/views/login/admin-login.html");
            }
            return false;
        }
    }
    private static boolean isAjax(ServletRequest request){
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if("XMLHttpRequest".equalsIgnoreCase(header)){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

}
